import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

// 提醒事项数据结构
export interface Reminder {
  id: string
  title: string
  notes: string
  completed: boolean
  priority: 'none' | 'low' | 'medium' | 'high'
  dueDate: string | Date | null
  dueTime: string | null
  tags: string[]
  listId: string
  createdAt: number
  completedAt: number | null
}

// 提醒列表数据结构
export interface ReminderList {
  id: string
  name: string
  icon: string
  color: string
  isSystem: boolean
}

export const useRemindersStore = defineStore('reminders', () => {
  // 预定义的系统列表
  const systemLists = ref<ReminderList[]>([
    { id: 'today', name: '今天', icon: '📅', color: '#007AFF', isSystem: true },
    { id: 'scheduled', name: '计划', icon: '📆', color: '#FF3B30', isSystem: true },
    { id: 'all', name: '全部', icon: '📋', color: '#5856D6', isSystem: true },
    { id: 'flagged', name: '已标记', icon: '🚩', color: '#FF9500', isSystem: true },
    { id: 'completed', name: '已完成', icon: '✓', color: '#34C759', isSystem: true },
  ])

  // 用户自定义列表
  const customLists = ref<ReminderList[]>([
    { id: 'list-1', name: '工作', icon: '💼', color: '#007AFF', isSystem: false },
    { id: 'list-2', name: '个人', icon: '👤', color: '#34C759', isSystem: false },
  ])

  // 所有提醒事项
  const reminders = ref<Reminder[]>([
    {
      id: '1',
      title: '完成项目报告',
      notes: '需要包含上季度的数据分析',
      completed: false,
      priority: 'high',
      dueDate: new Date().toISOString().split('T')[0],
      dueTime: '18:00',
      tags: ['工作', '重要'],
      listId: 'list-1',
      createdAt: Date.now() - 86400000,
      completedAt: null
    },
    {
      id: '2',
      title: '购买生活用品',
      notes: '',
      completed: false,
      priority: 'medium',
      dueDate: new Date().toISOString().split('T')[0],
      dueTime: null,
      tags: [],
      listId: 'list-2',
      createdAt: Date.now() - 172800000,
      completedAt: null
    },
    {
      id: '3',
      title: '健身房锻炼',
      notes: '记得带运动鞋',
      completed: true,
      priority: 'none',
      dueDate: new Date(Date.now() - 86400000).toISOString().split('T')[0],
      dueTime: '19:00',
      tags: ['健康'],
      listId: 'list-2',
      createdAt: Date.now() - 259200000,
      completedAt: Date.now() - 86400000
    },
  ])

  // 当前选中的列表
  const selectedListId = ref<string>('today')
  
  // 当前选中的提醒事项
  const selectedReminderId = ref<string | null>(null)

  // 持久化存储key
  const REMINDERS_STORAGE_KEY = 'vue-desktop:reminders'
  const LISTS_STORAGE_KEY = 'vue-desktop:reminder-lists'

  // 计算属性：所有列表
  const allLists = computed(() => [...systemLists.value, ...customLists.value])

  // 计算属性：当前选中的列表
  const selectedList = computed(() => 
    allLists.value.find(list => list.id === selectedListId.value)
  )

  // 计算属性：当前选中的提醒事项
  const selectedReminder = computed(() => 
    reminders.value.find(reminder => reminder.id === selectedReminderId.value)
  )

  // 计算属性：根据选中列表过滤的提醒事项
  const filteredReminders = computed(() => {
    const today = new Date().toISOString().split('T')[0]
    
    switch (selectedListId.value) {
      case 'today':
        // 今天：显示今天到期的未完成提醒
        return reminders.value.filter(r => 
          !r.completed && r.dueDate === today
        )
      
      case 'scheduled':
        // 计划：显示所有有日期的未完成提醒
        return reminders.value.filter(r => 
          !r.completed && r.dueDate !== null
        ).sort((a, b) => {
          if (!a.dueDate) return 1
          if (!b.dueDate) return -1
          return a.dueDate.localeCompare(b.dueDate)
        })
      
      case 'all':
        // 全部：显示所有未完成提醒
        return reminders.value.filter(r => !r.completed)
      
      case 'flagged':
        // 已标记：显示高优先级的未完成提醒
        return reminders.value.filter(r => 
          !r.completed && (r.priority === 'high' || r.priority === 'medium')
        )
      
      case 'completed':
        // 已完成：显示所有已完成提醒
        return reminders.value.filter(r => r.completed)
          .sort((a, b) => (b.completedAt || 0) - (a.completedAt || 0))
      
      default:
        // 自定义列表：显示该列表的所有未完成提醒
        return reminders.value.filter(r => 
          r.listId === selectedListId.value && !r.completed
        )
    }
  })

  // 计算属性：各列表的提醒数量
  const listCounts = computed(() => {
    const counts: Record<string, number> = {}
    const today = new Date().toISOString().split('T')[0]
    
    // 今天
    counts.today = reminders.value.filter(r => 
      !r.completed && r.dueDate === today
    ).length
    
    // 计划
    counts.scheduled = reminders.value.filter(r => 
      !r.completed && r.dueDate !== null
    ).length
    
    // 全部
    counts.all = reminders.value.filter(r => !r.completed).length
    
    // 已标记
    counts.flagged = reminders.value.filter(r => 
      !r.completed && (r.priority === 'high' || r.priority === 'medium')
    ).length
    
    // 已完成
    counts.completed = reminders.value.filter(r => r.completed).length
    
    // 自定义列表
    customLists.value.forEach(list => {
      counts[list.id] = reminders.value.filter(r => 
        r.listId === list.id && !r.completed
      ).length
    })
    
    return counts
  })

  // ==================== 提醒事项操作 ====================

  // 添加提醒事项
  function addReminder(reminder: Omit<Reminder, 'id' | 'createdAt' | 'completedAt'>) {
    const newReminder: Reminder = {
      ...reminder,
      id: `reminder-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      createdAt: Date.now(),
      completedAt: null
    }
    reminders.value.push(newReminder)
    saveRemindersToStorage()
    return newReminder
  }

  // 更新提醒事项
  function updateReminder(id: string, updates: Partial<Reminder>) {
    const index = reminders.value.findIndex(r => r.id === id)
    if (index !== -1) {
      reminders.value[index] = { ...reminders.value[index], ...updates }
      saveRemindersToStorage()
      return true
    }
    return false
  }

  // 切换完成状态
  function toggleReminderComplete(id: string) {
    const reminder = reminders.value.find(r => r.id === id)
    if (reminder) {
      reminder.completed = !reminder.completed
      reminder.completedAt = reminder.completed ? Date.now() : null
      saveRemindersToStorage()
      return true
    }
    return false
  }

  // 删除提醒事项
  function deleteReminder(id: string) {
    const index = reminders.value.findIndex(r => r.id === id)
    if (index !== -1) {
      reminders.value.splice(index, 1)
      if (selectedReminderId.value === id) {
        selectedReminderId.value = null
      }
      saveRemindersToStorage()
      return true
    }
    return false
  }

  // ==================== 列表操作 ====================

  // 添加自定义列表
  function addList(list: Omit<ReminderList, 'id' | 'isSystem'>) {
    const newList: ReminderList = {
      ...list,
      id: `list-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      isSystem: false
    }
    customLists.value.push(newList)
    saveListsToStorage()
    return newList
  }

  // 更新列表
  function updateList(id: string, updates: Partial<ReminderList>) {
    const index = customLists.value.findIndex(l => l.id === id)
    if (index !== -1) {
      customLists.value[index] = { ...customLists.value[index], ...updates }
      saveListsToStorage()
      return true
    }
    return false
  }

  // 删除列表
  function deleteList(id: string) {
    const index = customLists.value.findIndex(l => l.id === id)
    if (index !== -1 && !customLists.value[index].isSystem) {
      // 删除列表中的所有提醒事项
      reminders.value = reminders.value.filter(r => r.listId !== id)
      customLists.value.splice(index, 1)
      
      if (selectedListId.value === id) {
        selectedListId.value = 'today'
      }
      
      saveListsToStorage()
      saveRemindersToStorage()
      return true
    }
    return false
  }

  // ==================== 选择操作 ====================

  function selectList(listId: string) {
    selectedListId.value = listId
    selectedReminderId.value = null
  }

  function selectReminder(reminderId: string | null) {
    selectedReminderId.value = reminderId
  }

  // ==================== 持久化 ====================

  function saveRemindersToStorage() {
    try {
      localStorage.setItem(REMINDERS_STORAGE_KEY, JSON.stringify(reminders.value))
    } catch (error) {
      console.error('保存提醒事项失败:', error)
    }
  }

  function loadRemindersFromStorage() {
    try {
      const raw = localStorage.getItem(REMINDERS_STORAGE_KEY)
      if (raw) {
        reminders.value = JSON.parse(raw)
        return true
      }
    } catch (error) {
      console.error('加载提醒事项失败:', error)
    }
    return false
  }

  function saveListsToStorage() {
    try {
      localStorage.setItem(LISTS_STORAGE_KEY, JSON.stringify(customLists.value))
    } catch (error) {
      console.error('保存列表失败:', error)
    }
  }

  function loadListsFromStorage() {
    try {
      const raw = localStorage.getItem(LISTS_STORAGE_KEY)
      if (raw) {
        customLists.value = JSON.parse(raw)
        return true
      }
    } catch (error) {
      console.error('加载列表失败:', error)
    }
    return false
  }

  function clearRemindersCache() {
    reminders.value = []
    customLists.value = []
    selectedListId.value = 'today'
    selectedReminderId.value = null
    
    try {
      localStorage.removeItem(REMINDERS_STORAGE_KEY)
      localStorage.removeItem(LISTS_STORAGE_KEY)
    } catch (error) {
      console.error('清除提醒事项缓存失败:', error)
    }
  }

  // 初始化：加载数据
  loadRemindersFromStorage()
  loadListsFromStorage()

  return {
    // 状态
    systemLists,
    customLists,
    reminders,
    selectedListId,
    selectedReminderId,
    
    // 计算属性
    allLists,
    selectedList,
    selectedReminder,
    filteredReminders,
    listCounts,
    
    // 提醒事项操作
    addReminder,
    updateReminder,
    toggleReminderComplete,
    deleteReminder,
    
    // 列表操作
    addList,
    updateList,
    deleteList,
    
    // 选择操作
    selectList,
    selectReminder,
    
    // 持久化
    saveRemindersToStorage,
    loadRemindersFromStorage,
    saveListsToStorage,
    loadListsFromStorage,
    clearRemindersCache
  }
})

